var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: [],
    phone: '',
    state: true,
    canShowCode: false,
    code: '',
    zhengImg: [],
    fanImg: [],
    identity: '',
    desc: '',
    address: '',
    imgArrayDisability: [],
    imgArrayOther: [],
    sum: 0,
    mac: 'D5251D1E3588',
    showThis: true,
    VerifyCode: "获取验证码",
    zhengImgId: [],
    fanImgId: [],
    imgArrayDisabilityId: [],
    imgArrayOtherId: [],
    zArr: {},
    fArr: {},
    cArr: {},
    oArr: {},
    isOk:0,
    read:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      phone: wx.getStorageSync('iphone'),
      mac: options.mac,
      // mac: options.mac
    })
    let nophone = app.getUserLoginNoPhone();
    if (nophone && nophone == 2) {
      that.setData({
        state: false
      })
    } else {}
    that.getInfo()
  },
  // 选择身份证正面
  chooseImage(e) {
    let that = this;
    console.log(e)
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          zhengImg: res.tempFilePaths
        })
        console.log(that.data.zhengImg)
      }
    })
  },
  // 选择身份证反面
  chooseImageFan(e) {
    let that = this;
    console.log(e)
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          fanImg: res.tempFilePaths
        })
        console.log(res)
      }
    })
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  // 获取经纬度
  getLocation() {
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        console.log(res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + that.data.latitude + ',' + that.data.longitude + '&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77',
          success: function (result) {
            console.log(result.data.result.address_component.city)
          },
          fail() {
            console.log('请求失败')
          }
        })
      }
    })
  },

  // 获取手机号
  getPhoneNumber(e) {
    console.log(e)
    var that = this
    if (e.detail.errMsg.indexOf('user deny') != -1) {
      return;
    } else {
      wx.showLoading({
        title: '登录中...',
      });
      //解密数据并登录成功
      app.executeRequest(function (header) {

        wx.request({
          url: app.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
          header: header,
          data: {
            iv: encodeURIComponent(e.detail.iv),
            encryptedData: encodeURIComponent(e.detail.encryptedData)
          },
          success: function (res) {
            getApp().hideLoading();
            console.log('getPhoneNumber--res', res);
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            if (res.data.result === 0) {
              //登录成功
              wx.showToast({
                title: '登录成功',
              });
              var btt = that.data.phoneAuthBtt;

              wx.setStorageSync('nophone', '2');
              app.globalData.loginData.nophone = 2;
              wx.setStorageSync('iphone', res.data.phone)
              that.setData({
                phone: res.data.phone ? res.data.phone : '',
                state: false
              })
            } else if (res.data.result === 4) {
              wx.showToast({
                title: res.data.description,
                icon: "none"
              });
            } else {
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'scan',
                loading_show: false
              });
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              })
            }
          },
          fail: function (err) {
            getApp().hideLoading();
          }
        });

      });
    }
  },
  // 手机号验证
  changeInput(e) {
    console.log(e.detail.value)
    var that = this
    clearTimeout(that.data.time)
    that.data.time = setTimeout(() => {
      that.setData({
        phone: e.detail.value
      })
    }, 500);
  },
  getPhoneCode: function (e) {
    console.log("---phonenum=" + this.data.phone)
    if (this.data.phone != '') {
      var total_micro_second = 60 * 1000;
      //验证码倒计时
      this.count_down(this, total_micro_second);
      var url = "/lease_msg/validateCode";
      // var url = "/lease_msg/tcpcode";
      var phone = this.data.phone;
      wx.request({
        url: app.BASE_URL + url,
        header: app.getHeader(),
        data: {
          phone: phone
        },
        success: function (res) {
          console.log("发送短信成功")
          console.log(res)
        },
        fail: function (res) {
          console.log("发送短信失败")
          console.log(res)
        }
      })
    } else if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号'
      })
    } else {
      wx.showToast({
        title: '短信发送中'
      })
    }
  },
  count_down(that, total_micro_second) {
    var that = this
    if (total_micro_second <= 0) {
      that.setData({
        VerifyCode: "重新发送",
        getPhoneStat: true
      })
      // timeout则跳出递归
      return;
    }
    // 渲染倒计时时钟
    that.setData({
      VerifyCode: this.date_format(total_micro_second) + " 秒"
    });
    setTimeout(function () {
      // 放在最后--
      total_micro_second -= 1000;
      that.count_down(that, total_micro_second);
    }, 1000)
  },
  date_format(micro_second) {
    // 秒数
    var second = Math.floor(micro_second / 1000);
    var sec = this.fill_zero_prefix(second); // equal to => var sec = second % 60;
    return sec;
  },
  fill_zero_prefix(num) {
    return num < 10 ? "0" + num : num
  },
  // 身份证验证
  identityChange(e) {
    console.log(e.detail.value)
    var that = this
    clearTimeout(that.data.time)
    that.data.time = setTimeout(() => {
      that.setData({
        identity: e.detail.value
      })
    }, 500);
  },
  // 验证码验证
  changeInputCode(e) {
    var that = this
    clearTimeout(that.data.time)
    that.data.time = setTimeout(() => {
      that.setData({
        code: e.detail.value
      })
    }, 500);
  },
  // 改变姓名
  changeName(e) {
    var that = this
    clearTimeout(that.data.time)
    that.data.time = setTimeout(() => {
      that.setData({
        userName: e.detail.value
      })
    }, 500);
  },
  canShowCodeChange() {
    var that = this
    that.setData({
      canShowCode: true
    })
  },
  setImgArrDisability(e) {
    let that = this;
    console.log(e)
    let imgArrayDisability = e.detail;
    that.setData({
      imgArrayDisability: imgArrayDisability
    });
    console.log(imgArrayDisability, 'imgArrayDisability')
  },
  setImgArrOther(e) {
    console.log(e)
    let that = this;
    let imgArrayOther = e.detail;
    that.setData({
      imgArrayOther: imgArrayOther
    });
    console.log(imgArrayOther, 'imgArrayOther')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 改变地址
  addressChange(e) {
    this.setData({
      address: e.detail.value
    })
  },
  // 预览图片
  preViewImgs: function (e) {
    console.log(e)
    let current = e.currentTarget.dataset.current;
    let urls = e.currentTarget.dataset.urls;
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  // 备注
  blurValue(e) {
    this.setData({
      desc: e.detail.value
    })
  },
  jumpNav() {
    var that = this
    if(!this.data.read) {
      wx.showToast({
        title: '勾选阅读协议',
      })
      return
    }
    // 验证姓名
    if (!(/^[\u2E80-\u9FFF]+$/.test(that.data.userName))) {
      wx.showToast({
        title: '姓名有误！',
      })
      return
    }
    // 验证手机号
    if (!(/^1[3456789]\d{9}$/.test(that.data.phone))) {
      wx.showToast({
        title: '手机号有误！',
      })
      return
    }
    // 验证身份证信息
    if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(that.data.identity))) {
      wx.showToast({
        title: '身份证有误！',
      })
      return
    }
    // 验证省市区
    if (that.data.region.length == 0) {
      wx.showToast({
        title: '城市地址有误！',
      })
      return
    }
    if (that.data.zhengImg.length > 0) {
      console.log(that.data.zhengImg, 'uploadFile:fail createUploadTask:fail file not foundzheng')
      that.upLoadImg(app.getHeader(), that.data.zhengImg, 0, [], function (res) {
        console.log(res, '正面')
        let sum = that.data.sum
        sum++
        that.setData({
          zhengImgId: res,
          sum: sum
        })
        console.log(that.data.sum, 'zheng')
        that.upload()
      },that.data.zArr)
    } else {
      wx.showToast({
        title: '请上传照片',
      })
      return;
    }
    if (that.data.fanImg.length > 0) {
      that.upLoadImg(app.getHeader(), that.data.fanImg, 0, [], function (res) {
        console.log(res, '反面')
        let sum = that.data.sum
        sum++
        that.setData({
          fanImgId: res,
          sum: sum
        })
        console.log(that.data.sum, 'fan')
        that.upload()
      },that.data.fArr)
    } else {
      wx.showToast({
        title: '请上传照片',
      })
      return;
    }
    if (that.data.imgArrayDisability.length > 0) {
      that.upLoadImg(app.getHeader(), that.data.imgArrayDisability, 0, [], function (res) {
        console.log(res, '残疾证')
        let sum = that.data.sum
        sum++
        that.setData({
          imgArrayDisabilityId: res,
          sum: sum
        })
        console.log(that.data.sum, 'can')
        that.upload()

      },that.data.cArr)
    } else {
      wx.showToast({
        title: '请上传照片',
      })
      return;
    }
    if (that.data.imgArrayOther.length > 0) {
      that.upLoadImg(app.getHeader(), that.data.imgArrayOther, 0, [], function (res) {
        console.log(res, '其他证')
        let sum = that.data.sum
        sum++
        that.setData({
          imgArrayOtherId: res,
          sum: sum
        })
        console.log(that.data.sum, 'other')
        that.upload()
      },that.data.oArr)
    } else {
      let sum = that.data.sum
      sum++
      that.setData({
        sum: sum
      })
      that.upload()
    }

  },
  upload() {
    var that = this
    console.log(that.data.sum)
    if (that.data.sum == 4) {
      app.executeRequest(function (header) {
        wx.request({
          url: app.BASE_URL + '/validateInfo/add',
          header: header,
          method: 'POST',
          data: {
            userName: that.data.userName, // 姓名
            userIdNumber: that.data.identity, // 身份证号
            phone: that.data.phone, // 手机号
            // that.data.code,// 验证码
            province: that.data.region[0], // 省
            city: that.data.region[1], // 市
            village: that.data.region[2], // 区
            address: that.data.address, // 地址
            memo: that.data.desc, // 备注
            userIdNumFront: that.data.zhengImgId.join(), // 身份证正面
            userIdNumBack: that.data.fanImgId.join(), // 身份证反面
            userDisabilityCertificate: that.data.imgArrayDisabilityId.join(), // 残疾证
            userOtherCertificate: that.data.imgArrayOtherId.join(), // 其他证件
            mac: that.data.mac,
            code: that.data.code,
          },
          success: function (res) {
            console.log(res)
            if (res.data.result === 0) {
              that.setData({
                sum:0
              })
              wx.redirectTo({
                url: '../vsubmitApplications/vsubmitApplications',
              })
            }
          }
        });

      });
    }
  },
  // 获取详情
  getInfo() {
    var that = this
    console.log(that.data.sum)
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/validateInfo/get',
        header: header,
        method: 'POST',
        data: {

        },
        success: function (res) {
          console.log(res)
          let data = res.data.data
          if (res.data.result === 0) {
            that.setData({
              userName: data.userName, // 姓名
              identity: data.userIdNumber, // 身份证号
              phone: data.phone, // 手机号
              // that.data.code,// 验证码
              province: data.province, // 省
              city: data.city, // 市
              village: data.village, // 区
              address: data.address, // 地址
              desc: data.memo, // 备注
              zhengImgStr: data.userIdNumFront, // 身份证正面字符串
              fanImgStr: data.userIdNumBack, // 身份证反面字符串
              imgArrayDisability: data.disabilityImgs, // 残疾证
              imgArrayOther: data.otherImgs, // 其他证件
              // mac: data.mac,
              zhengImgIdES: data.userIdNumFrontId, //正面ID数组
              fanImgIdES: data.userIdNumBackId, //反面ID数组
              imgArrayDisabilityIdES: data.userDisabilityCertificate, //残疾证ID数组
              imgArrayOtherIdES: data.userOtherCertificate, //其他ID数组
              isOk:data.isOk,
              created:data.created,
              showThis: false
            })
            if(that.data.isOk == 1){
              wx.redirectTo({
                url: '../vsubmitApplications/vsubmitApplications?created='+that.data.created,
              })
            }
            that.data.zhengImg.push(that.data.zhengImgStr)
            that.data.fanImg.push(that.data.fanImgStr)
            that.data.zhengImgId.push(that.data.zhengImgIdES)
            that.data.fanImgId.push(that.data.fanImgIdES)

            that.setData({
              zhengImg: that.data.zhengImg,
              fanImg: that.data.fanImg,
              zhengImgId: that.data.zhengImgId, //正面id数组
              fanImgId: that.data.fanImgId, //反面id数组
              imgArrayDisabilityId: that.data.imgArrayDisabilityIdES.split(','), //残疾id数组
              imgArrayOtherId: that.data.imgArrayOtherIdES.split(','), //其他id数组
            })
            var zArr = {}
            var fArr = {}
            var cArr = {}
            var oArr = {}
            for (let i = 0; i < that.data.zhengImgId.length; i++) {
              zArr[that.data.zhengImg[i]] = that.data.zhengImgId[i]
              console.log(zArr, 'zArr')
            }
            for (let i = 0; i < that.data.fanImgId.length; i++) {
              fArr[that.data.fanImg[i]] = that.data.fanImgId[i]
              console.log(fArr, 'fArr')
            }
            for (let i = 0; i < that.data.imgArrayDisabilityId.length; i++) {
              cArr[that.data.imgArrayDisability[i]] = that.data.imgArrayDisabilityId[i]
              console.log(cArr, 'cArr')
            }
            for (let i = 0; i < that.data.imgArrayOtherId.length; i++) {
              oArr[that.data.imgArrayOther[i]] = that.data.imgArrayOtherId[i]
              console.log(oArr, 'oArr')
            }
            that.setData({
              zArr: zArr,
              fArr: fArr,
              cArr: cArr,
              oArr: oArr,
            })
            // 地址
            let cpdd = [that.data.province, that.data.city, that.data.village]
            that.setData({
              region: cpdd
            })
          }
        }
      });

    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 上传图片到服务器 start
  upLoadImg(header, imgUrlArray, index, imgIdArray, callback, pictrueArr = null) {
    var that = this
    var i = index ? index : 0
    var imgIdArray = imgIdArray || []
    if (imgUrlArray.length > 0) {
      console.log(imgUrlArray, 'imgUrlArray')
      if (pictrueArr) {
        let imgUrl = imgUrlArray[i];
        let imgId = pictrueArr.hasOwnProperty(imgUrl) ? pictrueArr[imgUrl] : null;
        if (imgId) {
          i++
          imgIdArray.push(imgId)
          if (i == imgUrlArray.length) { //当图片传完时，停止调用
            callback(imgIdArray)
          } else { //若图片还没有传完，则继续调用函数
            that.upLoadImg(header, imgUrlArray, i, imgIdArray, callback, pictrueArr);
          }
        } else {
          wx.uploadFile({
            url: app.BASE_URL + '/upload/img',
            header,
            filePath: imgUrlArray[i],
            name: 'file',
            success: function (res) {
              res = JSON.parse(res.data)
              if (res.result == 0) {
                i++
                imgIdArray.push(res.data)
                if (i == imgUrlArray.length) { //当图片传完时，停止调用
                  callback(imgIdArray)
                } else { //若图片还没有传完，则继续调用函数
                  that.upLoadImg(header, imgUrlArray, i, imgIdArray, callback, pictrueArr);
                }
              }
            },
            fail: function (err) {
              console.log("upImgFail", err);
            }
          })
        }
      } else {
        wx.uploadFile({
          url: app.BASE_URL + '/upload/img',
          header,
          filePath: imgUrlArray[i],
          name: 'file',
          success: function (res) {
            res = JSON.parse(res.data)
            if (res.result == 0) {
              i++
              imgIdArray.push(res.data)
              if (i == imgUrlArray.length) { //当图片传完时，停止调用
                callback(imgIdArray)
              } else { //若图片还没有传完，则继续调用函数
                that.upLoadImg(header, imgUrlArray, i, imgIdArray, callback, pictrueArr);
              }
            }
          },
          fail: function (err) {
            console.log("upImgFail", err);
          }
        })
      }
    } else {
      callback(imgIdArray)
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 删除图片
   */
  deleteImgZ: function (e) {
    let that = this
    let deleteIndex = e.currentTarget.dataset.index
    that.data.zhengImg.splice(deleteIndex, 1)
    that.setData({
      zhengImg: that.data.zhengImg
    })
  },
  /**
   * 删除图片
   */
  deleteImgF: function (e) {
    let that = this
    let deleteIndex = e.currentTarget.dataset.index
    that.data.fanImg.splice(deleteIndex, 1)
    that.setData({
      fanImg: that.data.fanImg
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  toViewServicePro: function () {
    wx.navigateTo({
      url: '../service_pro/ser_pro/service_pro',
    })
  },

  toViewPrivatePro:function () {
    wx.navigateTo({
      url: '../service_pro/priv_pro/private_pro',
    })
  },

  radioChange: function (e) {
    let that = this
    console.log(e)
    that.setData({
      read: !that.data.read
    })
  }

})